package com.biscuit.page.basicservice.design.search.strategy;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.biscuit.page.basicservice.api.model.response.search.SearchSuggestAResp;
import com.biscuit.page.basicservice.design.search.SearchHandlerContext;
import com.biscuit.page.basicservice.utils.HttpUtil;
import com.biscuit.page.basicservice.utils.JsonUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author biscuit
 * @createTime 2024/6/8 9:12
 */
public class SoGouSearchHandlerStrategy implements SearchHandlerStrategy {

    private SearchHandlerContext context;

    @Override
    public List<SearchSuggestAResp.SuggestAResp> suggest() {
        // 向 搜狗 请求关联词的请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("key", context.getKeyword());

        // 调用 搜狗 的搜索接口，获取联想词列表
        String resultJson = HttpUtil.get(context.getSearchEngineTypeEnum().getSourceUrl(), paramMap);

        // 结果非空判断
        if (StringUtils.isBlank(resultJson)) {
            return new ArrayList<>();
        }

        // 截取响应中的有效信息
        String json = resultJson.replaceAll(".*?\\((.*)\\)", "$1");

        // 获取响应中的有效信息
        List<Object> listObj = JsonUtil.parseList(json, Object.class);
        if (!(CollectionUtils.isNotEmpty(listObj) && listObj.size() > 2 && Objects.nonNull(listObj.get(1))) && listObj.get(1).toString().length() >= 2) {
            return new ArrayList<>();
        }

        List<String> suggestList = Arrays.asList(
                listObj.get(1).toString().substring(1, listObj.get(1).toString().length() - 1).split(",")
        );

        // 将有效数据转换为响应所需格式，并返回结果
        return suggestList.stream().map(x -> {
            SearchSuggestAResp.SuggestAResp data = new SearchSuggestAResp.SuggestAResp();
            data.setText(x);
            data.setRedirectUrl(context.getSearchEngineTypeEnum().getTargetUrl() + "?query=" + x);
            return data;
        }).collect(Collectors.toList());
    }

    @Override
    public void setContext(SearchHandlerContext context) {
        this.context = context;
    }
}
